<?php
namespace Common\Model;
use Think\Model;
class UserModel extends Model{
	public $tips_info = '未知错误！';//提示信息

	/**
	 * 客服人员
	 * @param  string $city_id [description]
	 * @return [type]          [description]
	 */
	public function admin_user_list($city_id = '', $role_id = ''){
		if($city_id > 0){
			$where['city_id'] = array(array('eq', $city_id), array('eq', 0), 'or');
		}
		if($role_id){
			$where['role_id'] = array('in', $role_id);
		}
		$where['status']  = 1;
		$list = D('Admin')->where($where)->select();

		return $list;
	}
	/**
	 * 后台管理用户姓名
	 * @param  [type] $user_id 后台用户ID
	 */
	public function get_admin_name($user_id){
		$where['id'] = $user_id;
		$admin_name = D('Admin')->where($where)->getField('realname');
		return $admin_name ? $admin_name : '';
	}
	public function get_admin_info($user_id){
		if(!$user_id){
			return array();
		}
		$where['id'] = $user_id;
		$info = D('Admin')->where($where)->find();
		$info['head_url']          = $info['head_id'] ? D('File')->get_path($info['head_id']) : '';
		$info['weixin_qrcode_url'] = $info['weixin_qrcode_id'] ? D('File')->get_path($info['weixin_qrcode_id']) : '';

		return $info;
	}
	/**
	 * 后台管理用户手机号
	 * @param  [type] $user_id 后台用户ID
	 */
	public function get_admin_mobile($user_id){
		$where['id'] = $user_id;
		$mobile = D('Admin')->where($where)->getField('mobile');
		return $mobile ? $mobile : '';
	}
	/**
	 * 获取用户设备唯一
	 * @param  [type] $user_id 用户ID
	 */
	public function get_device_alias($user_id){
		$where['user_id']     = is_array($user_id) ? array('in', implode(',', $user_id)) : $user_id;
		$where['create_time'] = array('gt', 0);
		$token = D('UserToken')->where($where)->getField('token', true);
		return $token ? $token : '';
	}
	//清单用户TOKEN
	public function clear_token($user_id){
		$where['user_id'] = $user_id;
		$data['create_time'] = 0;
		D('UserToken')->where($where)->save($data);
	}
	/**
	 * 生成用户ID
	 */
	public function generate_user_id(){
		//随机生成9位数的用户ID
		$chars   = str_repeat('012356789',3);
		$chars   = str_shuffle($chars);
		$user_id = substr($chars,0,9);
		//第一位为0的处理
		if(substr($user_id, 0,1) == 0){
			$rand_id = str_shuffle(str_replace('0', '', $user_id));
			$user_id = substr($rand_id, 0,1).substr($user_id, 1);
		}
		//如果存在，再次生成ID
		if($this->is_exists_id($user_id)){
			return $this->generate_user_id();
		}
		return $user_id;
	}
	/**
	 * 用户登录
	 * @param  string $user_name 手机号/E-mail
	 * @param  string $password  密码
	 */
	public function login($user_name = '', $password = ''){
		if(!$user_name){
			$this->tips_info = '手机号/E-mail不能为空！';
			return false;
		}
		if(!$password){
			$this->tips_info = '密码不能为空！';
			return false;
		}

		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $user_name) == false && is_numeric($user_name)){
			$this->tips_info = '对不起，手机号不正确！';
			return false;
		}

		//E-mail判断
		if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $user_name) && is_numeric($user_name) == false ) {
			$this->tips_info = '无效的 email 格式！';
			return false;
		}

		//获取用户信息
		$where['mobile'] = $user_name;
		$where['email']  = $user_name;
		$where['_logic'] = 'OR';
		$info = $this->where($where)->find();
		$user_id = $info['user_id'];

		//判断密码
		$password_md5 = password_md5_one($user_id, $password);
		if($info['password'] != $password_md5){
			$this->tips_info = '您的用户名或者密码有误！';
			return false;
		}
		//判断是否禁用
		if($info['status'] == 0){
			$this->tips_info = '您的账号被禁用，请联系相关人员！';
			return false;
		}

		//获取用户信息
		$user_info = $this->user_info($user_id);
		$user_info['token'] = $this->make_token($user_id);
		// 更新登录信息
		$data['login_num']  = array('exp', 'login_num + 1');
		$data['login_time'] = time();
		$this->where(array('user_id' => $user_id))->save($data);
		
		return $user_info;
	}
	/**
	 * 用户注册
	 * @param  string  $mobile    手机号
	 * @param  string  $email     E-mail
	 * @param  string  $password  密码，一次MD5加密小写
	 * @param  integer $is_lawyer 是否为律师
	 */
	public function register($mobile = '', $email = '', $password = '', $is_lawyer = 0, $reg_source = 'web'){
		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $mobile) == false){
			$this->tips_info = '对不起，手机号不正确！';
			return false;
		}
		//判断手机号是否注册过
		if($this->mobile_exists($mobile)){
			$this->tips_info = '对不起，手机号已存在！';
			return false;
		}
		//E-mail判断
		if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
			$this->tips_info = '无效的 email 格式！';
			return false;
		}
		//清空验证码缓存
		S('API_SMSCODE_' . $mobile, null);
		
		// 获取IP地址城市信息
		$city_info = D('Area')->ip2city();
		if($city_info['city_id'] && $city_info['province_id']){
			$data['province_id'] = $city_info['province_id'];
			$data['city_id']     = $city_info['city_id'];
		}
		//再次MD5加密
		$user_id = $this->generate_user_id();
		$data['user_id']     = $user_id;
		$data['mobile']      = $mobile;
		$data['email']       = $email;
		$data['is_lawyer']   = $is_lawyer ? 1 : 0;
		$data['service_id']  = $is_lawyer ? 0 : 7;//客服ID
		$data['password']    = password_md5_one($user_id, $password);
		$data['reg_source']  = $reg_source ? $reg_source : 'web';
		$data['create_time'] = time();
		$this->add($data);
		//开通律师账号
		if($is_lawyer){
			$this->open_lawyer_user($user_id);
		}
		//获取用户信息
		$user_info = $this->user_info($user_id);
		$user_info['token'] = $this->make_token($user_id);

		return $user_info;
	}
	//获取终端类型
	protected function get_app_type(){
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		if(preg_match("/(MicroMessenger)/si",$user_agent)){
			return 'weixin';
		}
		if(preg_match("/(Android)/si", $user_agent)){
			return 'android';
		}
		if(preg_match("/(windows phone)/si", $user_agent)){
			return 'wp';
		}
		if(preg_match("/(iPhone|iPad|iPod|iOS)/si", $user_agent)){
			return 'ios';
		}
		return 'web';
	}
	/**
	 * 开通律师用户
	 * @param  string $user_id 用户ID
	 */
	public function open_lawyer_user($user_id = ''){
		if(!$user_id){
			return false;
		}
		$where['user_id'] = $user_id;
		if(!D('UserLawyer')->where($where)->count()){
			$data['user_id']     = $user_id;
			$data['create_time'] = time();
			D('UserLawyer')->add($data);
		}
	}
	//获取用户TOKEN
	public function user_token(){
		return session('user_token');
	}
	/**
	 * 保存用户SESSION
	 * @param  string $user_info 用户信息
	 */
	public function save_session($user_info = ''){
		$time = 24 * 60 * 60;
		session(array('expire' => $time));
		//保存用户信息
		session('user_info', $user_info);
		//保存用户TOKEN
		session('user_token', $user_info['token']);
	}
	
	/**
	 * 获取用户信息
	 */
	public function get_user_info($is_login = true){
		$user_id = $this->login_user_id($is_login);
		if(!$user_id){
			return false;
		}
		//获取用户信息
		$user_info = $this->user_info($user_id);
		$user_info['token'] = $this->get_token($user_id);
		$this->save_session($user_info);
		return $user_info;
	}
	/**
	 * 获取用户城市信息
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_city_info($user_id){
		$where['user_id'] = $user_id;
		$info = D('User')->field('saas_enterprise_id,saas_user_id,province_id,city_id,area_id')->where($where)->find();

		$data['saas_enterprise_id'] = $info['saas_enterprise_id'] ? $info['saas_enterprise_id'] : 0;
		$data['saas_user_id']       = $info['saas_user_id'] ? $info['saas_user_id'] : 0;
		$data['province_id']        = $info['province_id'] ? $info['province_id'] : 0;
		$data['city_id']            = $info['city_id'] ? $info['city_id'] : 0;
		$data['area_id']            = $info['area_id'] ? $info['area_id'] : 0;

		return $data;
	}
	/**
	 * 获取用户登录TOKEN
	 */
	public function login_user_token(){
		$token = session('user_token');
		return $token ? $token : '';
	}
	/**
	 * 获取登录用户ID
	 * @param  boolean $is_login [description]
	 * @return [type]            [description]
	 */
	public function login_user_id($is_login = true){
		//获取token
		$token = session('user_token');
		if(!$token && $is_login){
			$this->login_timeout('对不起，您尚未登录！');
		}

		$where['token'] = $token;
		$info = D('UserToken')->where($where)->field('user_id,create_time')->find();
		if(!$info && $is_login){
			$this->login_timeout('登录超时，请重新登录[1]！');
		}
		//判断是否超时（2小时）
		$conf_timeout = C('LOGIN_TIMEOUT');
		$conf_timeout = $conf_timeout ? $conf_timeout : 7 * 24 * 60 * 60;
		// var_dump($conf_timeout);exit;
		$is_timeout = (time() - $info['create_time']) > $conf_timeout;
		if($is_timeout && $is_login){
			$this->login_timeout('登录超时，请重新登录[2]！');
		}
		if($is_login && $info){
			//刷新登录时间
			D('UserToken')->where($where)->save(array('create_time'=>time()));
		}
		
		return $info['user_id'] ? $info['user_id'] : 0;
	}
	public function edit_info($user_id, $realname = '', $nickname = '', $sex = '', $city_id = '', $area_id = '', $email = ''){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		//真实姓名
		if($realname){
			$data['realname'] = $realname;
		}
		//昵称
		if($nickname){
			$data['nickname'] = $nickname;
		}
		//性别
		if($sex){
			$data['sex'] = $sex;
		}
		//E-mail
		if($email){
			$data['email']         = $email;
			$data['is_auth_email'] = 0;
		}
		//地区ID
		if($area_id){
			//获取城市ID
			$city_id = D('Area')->get_parent_id($area_id);
			//获取省份ID
			if($city_id){
				$province_id = D('Area')->get_parent_id($city_id);

				$data['province_id'] = $province_id;
				$data['city_id']     = $city_id;
				$data['area_id']     = $area_id;
			}
		}
		//城市ID
		if($city_id && !$province_id){
			//获取城市ID
			$data['city_id']     = $city_id;
			//获取省份ID
			$data['province_id'] = D('Area')->get_parent_id($city_id);
		}
		if($data){
			$where['user_id'] = $user_id;
			$this->where($where)->save($data);
			$user_info = $this->user_info($user_id);
			return $user_info;
		}
		return false;
	}
	/**
	 * 修改律师信息
	 * @param  integer $user_id           用户ID
	 * @param  integer $identification_id 证件照片ID
	 * @param  integer $practice_no       执业证号
	 * @param  string  $work_unit         工作单位
	 * @param  integer $skilled_id        擅长领域
	 */
	public function edit_lawyer_info($user_id = 0, $identification_id = 0, $practice_no = 0, $work_unit = '', $skilled_id = 0){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if($identification_id){
			$data['identification_id'] = $identification_id;
		}
		if($practice_no){
			$data['practice_no'] = $practice_no;
		}
		if($work_unit){
			$data['work_unit'] = $work_unit;
		}
		if($skilled_id){
			$data['skilled_id'] = $skilled_id;
		}
		$data['edit_time'] = time();

		$this->open_lawyer_user($user_id);

		$where['user_id'] = $user_id;
		D('UserLawyer')->where($where)->save($data);

		return true;
	}
	/**
	 * 修改手机号
	 * @param  [type] $user_id 用户ID
	 * @param  [type] $mobile  手机号
	 */
	public function change_mobile($user_id, $mobile){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		//手机号判断
		if(preg_match('/^1[34578][0-9]{9}$/', $mobile) == false){
			$this->tips_info = '对不起，手机号不正确！';
			return false;
		}
		if($this->mobile_exists($mobile)){
			$this->tips_info = '您输入的手机号已经注册过，无法绑定！';
			return false;
		}
		//清空验证码缓存
		S('API_SMSCODE_' . $mobile, null);
		
		$data['mobile'] = $mobile;
		$this->where(array('user_id' => $user_id))->save($data);

		return true;
	}
	/**
	 * 修改用户SaaS信息
	 * @param  [type] $user_id            用户ID
	 * @param  [type] $saas_enterprise_id SaaS企业ID
	 * @param  [type] $saas_user_id       SaaS用户ID
	 */
	public function change_saas_info($user_id, $saas_enterprise_id, $saas_user_id){

		$data['saas_user_id']       = $saas_user_id ? intval($saas_user_id) : 0;
		$data['saas_enterprise_id'] = $saas_enterprise_id ? intval($saas_enterprise_id) : 0;

		$where['user_id'] = $user_id;
		$this->where($where)->save($data);
	}
	/**
	 * 修改E-mail
	 * @param  [type] $user_id 用户ID
	 * @param  [type] $email   E-mail
	 */
	public function change_email($user_id, $email){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		//E-mail判断
		if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) {
			$this->tips_info = '无效的 email 格式！';
			return false;
		}
		if($this->email_exists($email)){
			$this->tips_info = '您输入的E-mail已经注册过，无法绑定！';
			return false;
		}

		$data['email']         = $email;
		$data['is_auth_email'] = 0;
		$this->where(array('user_id' => $user_id))->save($data);

		return true;
	}
	/**
	 * 修改密码
	 * @param  [type] $user_id 			用户ID
	 * @param  [type] $old_password   	旧密码
	 * @param  [type] $new_password   	新密码
	 */
	public function change_password($user_id, $old_password = '', $new_password = ''){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		$where['user_id'] = $user_id;
		$info = $this->field('password')->where($where)->find();
		//判断旧密码是否正确
		$db_password  = $info['password'];
		$password_md5 = password_md5_one($user_id, $old_password);
		if($db_password != $password_md5){
			$this->tips_info = '您输入的旧密码有误！';
			return false;
		}

		//更新新密码
		$password_md5     = password_md5_one($user_id, $new_password);
		$data['password'] = $password_md5;
		$this->where($where)->save($data);

		return true;
	}
	/**
	 * 修改密码
	 * @param  [type] $user_id  用户ID
	 * @param  string $password 密码
	 */
	public function edit_password($user_id, $password = ''){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$password){
			$this->tips_info = '密码不能为空！';
			return false;
		}
		$where['user_id'] = $user_id;
		$data['password'] = password_md5_one($user_id, $password);;
		$this->where($where)->save($data);

		return true;
	}
	/**
	 * 找回密码
	 * @param  [type] $mobile   手机号
	 * @param  string $password 密码
	 */
	public function forget_password($mobile, $password = ''){
		if(!$mobile){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$password){
			$this->tips_info = '密码不能为空！';
			return false;
		}
		$user_id = $this->get_mobile_user_id($mobile);
		if(!$user_id){
			$this->tips_info = '手机号不存在！';
			return false;
		}
		$data['password'] = password_md5_one($user_id, $password);;
		$this->where(array('user_id' => $user_id))->save($data);

		return true;
	}
	/**
	 * 检查密码
	 * @param  [type] $user_id  用户ID
	 * @param  string $password 密码，MD5一次小写
	 */
	public function check_password($user_id, $password = ''){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$password){
			$this->tips_info = '密码不能为空！';
			return false;
		}

		//获取原密码
		$db_password = $this->where(array('user_id' => $user_id))->getField('password');
		if($db_password){
			//验证密码
			$check_password = password_md5_one($user_id, $password);
			//验证输入密码是否正确
			if($check_password != $db_password){
				$this->tips_info = '对不起，您输入密码不对！';
				return false;
			}
			return true;
		}
		return false;
	}
	/**
	 * 判断用户手机号是否存在
	 * @param  [type]  $mobile 手机号
	 * @return boolean         [description]
	 */
	public function mobile_exists($mobile){
		$where['mobile'] = $mobile;
		$count = $this->where($where)->count();
		return $count > 0;
	}
	/**
	 * 获取用户手机号
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_mobile($user_id){
		$where['user_id'] = $user_id;
		$mobile = $this->where($where)->getField('mobile');

		return $mobile ? $mobile : '';
	}
	/**
	 * 判断E-mial是否存在
	 * @param  [type]  $email E-mail
	 */
	public function email_exists($email){
		$where['email'] = $email;
		$count = $this->where($where)->count();
		return $count > 0;
	}
	/**
	 * 判断用户是否存在
	 * @param  [type]  $user_id 用户ID
	 * @return boolean          [description]
	 */
	public function is_exists_id($user_id){
		$where['user_id'] = $user_id;
		$count = $this->where($where)->count();
		return $count > 0;
	}
	/**
	 * 判断用户是否设置
	 * @param  [type]  $user_id 用户ID
	 */
	public function is_set_password($user_id){
		$where['user_id']  = $user_id;
		$where['password'] = array('neq', '');
		$count = $this->where($where)->count();
		return $count > 0;
	}
	/**
	 * 获取手机号用户ID
	 * @param  string $mobile 手机号
	 */
	public function get_mobile_user_id($mobile=''){
		$where['mobile'] = $mobile;
		$user_id = $this->where($where)->getField('user_id');
		return $user_id;
	}
	public function user_info($user_id){
		$where['user_id'] = $user_id;
		$data = $this->where($where)->find();

		$data['user_name']     = $this->get_user_name($user_id);
		$data['province_name'] = D('Area')->id2names($data['province_id']);
		$data['city_name']     = D('Area')->id2names($data['city_id']);
		$data['area_name']     = D('Area')->id2names($data['area_id']);
		$data['head_url']      = $this->get_user_head_url($user_id);
		$data['set_password']  = $data['password'] != '';

		// 律师账号信息
		$data['lawyer_info'] = array();
		if($data['is_lawyer']){
			$lawyer_info = $this->lawyer_info($user_id);
			$data['lawyer_info'] = $lawyer_info;
			$data['info_is_full'] = true;
			if(!$data['realname'] || !$data['sex'] || !$data['area_id'] || !$lawyer_info['identification_id'] || !$lawyer_info['practice_no'] || !$lawyer_info['work_unit'] || !$lawyer_info['skilled_id']){
				$data['info_is_full'] = false;
			}
		}

		//性别处理
		$data['sex_desc']  = get_type_desc($data['sex'], 'sex_desc');
		//用户绑定信息
		$data['bind_info'] = $this->get_bind_sso_info($user_id);

		return $data;
	}
	/**
	 * 律师用户信息
	 * @param  [type] $user_id 用户ID
	 */
	public function lawyer_info($user_id){
		$where['user_id'] = $user_id;
		$data = D('UserLawyer')->where($where)->find();

		if(!$data){
			return array();
		}

		$data['identification_url'] = D('File')->get_path($data['identification_id']);//证件照片URL
		$data['skilled_name']       = D('Category')->get_name($data['skilled_id']);//擅长领域
		$data['audit_status_desc']  = get_type_desc($data['audit_status'], 'lawyer_audit_status_desc');
		$data['audit_reason']       = $data['audit_status'] == 2 ? $this->get_audit_reasons($user_id, 'lawyer_user') : '';
		
		return $data;
	}
	/**
	 * 获取审核信息
	 * @param  string $type_id 审核ID
	 * @param  string $type    审核类型
	 */
	public function get_audit_reasons($type_id = '', $type = 'audit_contract'){
		$where['type']    = $type;
		$where['type_id'] = $type_id;
		$content = D('AuditReasons')->where($where)->order('id desc')->getField('content');

		return $content ? $content : '';
	}
	/**
	 * 获取用户积分
	 * @param  string $user_id 用户ID
	 */
	public function get_user_score($user_id = ''){
		$where['user_id'] = $user_id;
		$score = $this->where($where)->getField('score');

		return $score;
	}
	/**
	 * 获取用户名称
	 * @param  string $user_id 用户ID
	 */
	public function get_user_name($user_id = ''){
		$user_name = '';
		
		$where['user_id'] = $user_id;
		$info = $this->where($where)->find();
		if($info){
			$user_name = $info['realname'] ? $info['realname'] : substr_replace($info['mobile'], '****', 3, 4);
		}
		return $user_name;
	}
	/**
	 * 获取用户绑定第三方信息
	 * @param  [type] $user_id [description]
	 * @return [type]          [description]
	 */
	public function get_bind_sso_info($user_id){
		$data = array();
		$sso_bind = array('weibo', 'weixin', 'qq');
		foreach ($sso_bind as $type) {
			$where['user_id']  = $user_id;
			$where['sso_type'] = $type;
			$info = D('UserSso')->where($where)->find();
			$data['is_bind_' . $type] = $info['open_id'] != '';
			$data['nickname_' . $type] = $info['nickname'] ? $info['nickname'] : '';
		}
		return $data;
	}
	/**
	 * 获取用户头像URL
	 * @param  [type] $user_id 用户ID
	 */
	public function get_user_head_url($user_id){
		$where['user_id'] = $user_id;
		$info = $this->field('head_id,sex')->where($where)->find();
		$head_id = $info['head_id'];
		if(!$head_id){
			switch ($info['sex']) {
				//男头像
				case '1':
					$default_head = 'head-man-default.png';
					break;
				//女头像
				case '2':
					$default_head = 'head-woman-default.png';
					break;
				//默认头
				default:
					$default_head = 'head-man-default.png';
					break;
			}
		}
		$head_url = D('File')->get_path($head_id ? $head_id : $default_head);
		return $head_url;
	}
	/**
	 * 用户头像裁切
	 * @param  [type]  $user_id [description]
	 * @param  [type]  $file_id [description]
	 * @param  integer $x1      [description]
	 * @param  integer $y1      [description]
	 * @param  [type]  $x2      [description]
	 * @param  [type]  $y2      [description]
	 * @param  [type]  $width   [description]
	 * @param  [type]  $height  [description]
	 * @return [type]           [description]
	 */
	public function user_head_crop($user_id, $file_id, $x1 = 0, $y1 = 0, $x2, $y2, $width, $height){
		if(!$user_id){
			$this->tips_info = '用户ID不能为空！';
			return false;
		}
		if(!$file_id){
			$this->tips_info = '请选择图片！';
			return false;
		}
		$x1 = $x1 ? $x1 : 0;
		$y1 = $y1 ? $y1 : 0;
		if(!$x2){
			$this->tips_info = 'x2不能为空';
			return false;
		}
		if(!$y2){
			$this->tips_info = 'y2不能为空';
			return false;
		}
		if(!$width){
			$this->tips_info = 'width不能为空';
			return false;
		}
		if(!$height){
			$this->tips_info = 'height不能为空';
			return false;
		}
		
		$info = D('File')->get_file_info($file_id);
		if(!$info){
			$this->tips_info = '文件不存在！';
			return false;
		}
		if(!in_array($info['ext'], array('jpg', 'png', 'bmp', 'jpeg'))){
			$this->tips_info = '[' . $info['ext'] . ']此图片文件格式无法裁剪！';
			return false;
		}
		$crop_file_id = D('File')->crop($user_id, $file_id, $x1, $y1, $x2, $y2, $width, $height);
		if($crop_file_id){
			//更新头像
			D('User')->where(array('user_id' => $user_id))->save(array('head_id' => $crop_file_id));
			$data = D('File')->get_file_info($crop_file_id);
			return $data;
		}
		$this->tips_info = '裁剪失败！';
		return false;
	}
	/**
	 * 判断是否收藏
	 * @param  [type]  $user_id 用户ID
	 * @param  [type]  $fav_id  收藏ID
	 * @param  string  $type    收藏类型
	 */
	public function is_fav($user_id, $fav_id, $type = 'article'){
		$where['user_id'] = $user_id;
		$where['fav_id']  = $fav_id;
		$where['type']    = $type;

		$count = D('UserFav')->where($where)->count();

		return $count > 0;
	}
	/**
	 * 设置收藏
	 * @param [type] $user_id 用户ID
	 * @param [type] $fav_id  收藏ID
	 * @param string $type    收藏类型
	 */
	public function set_fav($user_id, $fav_id, $type = 'article'){

		$is_fav = $this->is_fav($user_id, $fav_id, $type);

		$where['user_id'] = $user_id;
		$where['fav_id']  = $fav_id;
		$where['type']    = $type;

		if($is_fav){
			D('UserFav')->where($where)->delete();
			if($type == 'article'){
				D('Article')->update_num($fav_id, 'fav_num', 'minus');
			}
			return 2;//取消收藏
		}else{
			$data = $where;
			$data['create_time'] = time();
			D('UserFav')->add($data);
			if($type == 'article'){
				D('Article')->update_num($fav_id, 'fav_num', 'add');
			}
			return 1;//添加收藏
		}
	}
	/**
	 * 获取用户收藏
	 * @param  [type] $user_id [description]
	 * @param  string $type    [description]
	 * @return [type]          [description]
	 */
	public function get_fav($user_id, $type = 'article', $page=1, $pagesize=10){
		$where['user_id'] = $user_id;
		$where['type']    = $type;

		$data['count'] = D('UserFav')->where($where)->count();
		$list  = D('UserFav')->where($where)->order('create_time desc')->select();
		foreach ($list as $rs) {
			$rs['fav_date'] = date('Y-m-d', $rs['create_time']);
			$rs['fav_dtime'] = date('Y-m-d H:i:s', $rs['create_time']);
			$new_list[] = $rs;
		}
		$data['list'] = $new_list;
		
		return $data;
	}
	//获取用户城市ID
	public function get_user_city_id($user_id){
		$where['user_id'] = $user_id;
		$city_id = $this->where($where)->getField('city_id');
		return $city_id;
	}
	/**
	 * 生成用户TOKEN
	 * @param  string  $user_id 用户ID
	 * @param  integer $type    登录类型 1Android 2iOS
	 * @param  integer $imei    设备唯一标识
	 * @param  integer $device  设备信息 如iPhone 5s
	 */
	public function make_token($user_id = '', $app_type = '', $imei = '', $device = ''){
		$token_model = D('UserToken');
		$imei        = $imei ? $imei : $_SERVER['HTTP_APP_IMEI'];
		$app_type    = $app_type ? $app_type : $_SERVER['HTTP_APP_TYPE'];
		$device      = $device ? $device  : $_SERVER['HTTP_APP_DEVICE'];

		$app_type = $app_type ? $app_type : 'web';
		//踢出其它设备登录用户
		$where['user_id']  = $user_id;
		$where['app_type'] = array('neq','web');//处理APP登录
		//处理WEB登录
		if($app_type == 'web'){
			$where['app_type'] = 'web';
		}
		$token_model->where($where)->save(array('create_time' => 0));

		unset($where);
		$where['user_id']  = $user_id;
		$where['app_type'] = $app_type;
		$old_token = $token_model->where($where)->getField('token');

		$token = md5($user_id . $app_type .uniqid());

		$data['app_type']    = $app_type;
		$data['user_id']     = $user_id;
		$data['token']       = $token;
		$data['ip']          = get_client_ip();
		$data['create_time'] = time();
		//设备信息
		$data['device'] = $device ? $device : '';
		//设备唯一标识
		$data['imei']   = $imei ? $imei : '';

		if($old_token){
			$where['token'] = $old_token;
			$token_model->where($where)->save($data);
		}else{
			$token_model->add($data);
		}
		return $token;
	}
	/**
	 * 获取用户现有TOKEN
	 * @param  [type] $user_id   用户ID
	 * @return [type]            TOKEN
	 */
	public function get_token($user_id, $app_type = ''){
		$app_type = $app_type ? $app_type : $_SERVER['HTTP_APP_TYPE'];
		$app_type = $app_type ? $app_type : 'web';

		$where['user_id']   = $user_id;
		$where['app_type']  = $app_type;
		$token = D('UserToken')->where($where)->getField('token');

		return $token ? $token : '';
	}
	/**
	 * 获取TOKEN的用户ID
	 * @param  string $token [description]
	 * @return [type]        [description]
	 */
	public function get_token_user_id($token=''){
		if(!$token){
			$get_token = $_REQUEST['token'];
			$app_token = $_SERVER['HTTP_APP_TOKEN'];
			$token     = $get_token ? $get_token : $app_token;
		}
		if(!$token){
			return 0;
		}
		$where['token'] = $token;
		$user_id = D('UserToken')->where($where)->getField('user_id');
		return $user_id ? $user_id : 0;
	}
	/**
	 * 单点登录（token）
	 * @param  [type] $token [description]
	 * @return [type]        [description]
	 */
	public function sso_login_token($token){
		$where['token']       = $token;
		$where['create_time'] = array('gt', 0);
		$user_id = D('UserToken')->where($where)->getField('user_id');
		if(!$user_id){
			return false;
		}
		//获取用户信息
		$user_info = $this->user_info($user_id);
		$user_info['token'] = $this->make_token($user_id);
		// 更新登录信息
		$data['login_num']  = array('exp', 'login_num + 1');
		$data['login_time'] = time();
		$this->where(array('user_id' => $user_id))->save($data);

		return $user_info;
	}
	/**
	 * 获取第三方用户ID
	 * @param  [type] $open_id  [description]
	 * @param  string $sso_type [description]
	 * @return [type]           [description]
	 */
	public function get_sso_user_id($open_id, $sso_type='weixin'){
		$where['sso_type'] = $sso_type;
		$where['open_id']  = $open_id;
		$user_id = D('UserSso')->where($where)->getField('user_id');
		return $user_id ? $user_id : '';
	}

	/**
	 * 是否绑定第三方账号
	 * @param  [type]  $user_id  用户ID
	 * @param  string  $sso_type 第三方类型，weixin微信
	 */
	public function is_bind($user_id,$sso_type='weixin'){
		$where['user_id']  = $user_id;
		$where['sso_type'] = $sso_type;
		$count = D('UserSso')->where($where)->count();
		return $count > 0;
	}

	/**
	 * 登录超时处理
	 */
	protected function login_timeout($msg = ''){
		$login_url = URL('Login/index', '', '/login');
		session('user_token', null);
		if(IS_AJAX){
			$this->json_error($msg ? $msg : $this->tips_info, array('url', $login_url), 202);
		}
		redirect($login_url);
		exit;
	}

	/**
	 * 返回错误信息
	 * @param  string $msg    [description]
	 * @param  [type] $data   [description]
	 * @param  [type] $status [description]
	 * @return [type]         [description]
	 */
	protected function json_error($msg = '', $data, $status = 400){
		$info['info']   = $msg;
		$info['data']   = $data;
		$info['status'] = $status;

		$json = json_encode($info);
		exit($json);
	}





	
}